package test.designmode.producerconsumer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者
 */
public class Producer implements Runnable {

    private BlockingQueue<Data> queue;

    private volatile boolean isRunning = true;

    private static AtomicInteger count = new AtomicInteger();

    public Producer(BlockingQueue<Data> queue) {
        this.queue = queue;
    }

    public void stop() {
        this.isRunning = false;
    }

    /**
     * 多线程里面的使用的变量都须斟酌,是否volatile是否用concurrent包下的东西
     */
    @Override
    public void run() {
        while (isRunning) {
            try {
                /* 模拟耗时 */
                Thread.sleep(1000);
                int newId = count.getAndIncrement();
                Data data = new Data(newId, "数据:" + newId);
                System.out.println("生产了数据:" + newId);
                queue.put(data);      // 队列满了就一直等到不满再put

                List<String> mylist = new ArrayList<>();
                for (String s : mylist) {

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
